import 'package:flutter/material.dart';
import 'package:goumao_app/Customs/gm_app_util.dart';
import 'package:goumao_app/Model/gm_cw_type_model.dart';

class GMCWTypeScreen extends StatefulWidget {
  const GMCWTypeScreen({super.key});

  @override
  // ignore: library_private_types_in_public_api
  _GMCWTypeScreenState createState() => _GMCWTypeScreenState();
}

class _GMCWTypeScreenState extends State<GMCWTypeScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  late final GMCWTypeModel typeModel;

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  // 生命周期函数， 加载即触发
  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 2);

    GMAppUtil.toLoadData("assets/mydata/gm_cw_type_list.json").then((data) {
      print(data);
      setState(() {
        typeModel = GMCWTypeModel.fromJson(data);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: const Text(
          '选择品种',
          style: GMAppUtil.kNavTextStyle,
        ),
        bottom: TabBar(
          controller: _tabController, // 使用TabbarController必须加，相当于设置监听
          tabs: const <Widget>[
            Tab(
              text: "狗狗",
            ),
            Tab(
              text: "猫猫",
            ),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: <Widget>[
          GMCWTypeListPage(
            typeDatas: typeModel.data![0].list!,
          ),
          GMCWTypeListPage(
            typeDatas: typeModel.data![1].list!,
          ),
        ],
      ),
    );
  }
}

class GMCWTypeListPage extends StatelessWidget {
  final List<GMCWTypeData>? typeDatas;
  const GMCWTypeListPage({super.key, required this.typeDatas});

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: ListView.builder(
      itemCount: typeDatas!.length,
      itemBuilder: (context, index) {
        GMCWTypeData data = typeDatas![index];
        String path = data.head!;
        bool isNet = false;
        if (path.contains("head")) {
          isNet = true;
        }
        return ListTile(
          onTap: () {
            Navigator.pop(context, data);
          },
          leading: ClipRRect(
            borderRadius: BorderRadius.circular(35),
            child: isNet
                ? Image.network(
                    "https://file.onepetmall.com/${typeDatas![index].head!}",
                    width: 48,
                    height: 48,
                  )
                : Image.asset(
                    "assets/${typeDatas![index].head!}",
                    width: 48,
                    height: 48,
                  ),
          ),
          title: Text(typeDatas![index].name!),
        );
      },
    ));
  }
}
